from flask import Flask, request, jsonify
from flask_cors import CORS
import json
import os

app = Flask(__name__)
CORS(app)  # 允许跨域

# 全局变量存储最新数据
latest_data = {
    "temperature": 23.5,
    "Humidity": 24.1,
    "WindSpeed": 5.2,
    "UV": 20.5,
    "AQI": 200,
    "LightLux": 20.5,
    "soilHumidity": 20.5,
    "IrrigationPumpStatus": 0,
    "FanLevel": 1,
    "LEDLux": 2
}


@app.route('/api/data', methods=['GET'])
def get_data():
    """获取当前环境数据"""
    return jsonify(latest_data)


@app.route('/api/control', methods=['POST'])
def control():
    """控制设备"""
    try:
        data = request.json
        print(f"收到控制命令: {data}")

        # 更新本地缓存
        latest_data.update(data)

        # 这里可以调用mqtt_python.py里的publish_params方法
        # 暂时注释掉，避免循环调用
        # from mqtt_python import publish_params
        # publish_params(json.dumps(data))

        return jsonify({"success": True, "message": "控制命令已发送"})
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


@app.route('/api/update_data', methods=['POST'])
def update_data():
    """更新环境数据（供MQTT回调使用）"""
    try:
        data = request.json
        latest_data.update(data)
        return jsonify({"success": True})
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 400


if __name__ == '__main__':
    print("启动Web API服务器...")
    print("访问地址: http://localhost:5000")
    app.run(host='0.0.0.0', port=5000, debug=True)
